<script setup>
const props = defineProps({
  expire: {
    type: Number,
    default: 120
  }
});

const emits = defineEmits(['end'])

let timer = null;
const time_out = ref(0)
const initTimeBox = () => {
  if (timer) {
    clearInterval(timer)
  }
  time_out.value = props.expire * 60;
  timer = setInterval(handleTimeOut, 1000)
}


const handleTimeOut = () => {
  if (time_out.value === 0) {
    emits('end')
    return clearInterval(timer)
  }

  time_out.value--;
}


// 秒 => 时分秒
const toHHmmss = (data) => {
  let s;
  let hours = parseInt((data % (60 * 60 * 24)) / (60 * 60));
  let minutes = parseInt((data % (60 * 60)) / 60);
  let seconds = data % 60;
  s = (hours < 10 ? ('0' + hours) : hours) + ":" + (minutes < 10 ? ('0' + minutes) : minutes) + ":" + (seconds < 10 ? ('0' + seconds) : seconds);
  return s;
}


onMounted(() => initTimeBox());
onBeforeUnmount(() => clearInterval(timer))
</script>

<template>
  <div>
    {{ toHHmmss(time_out) }}
  </div>
</template>

<style scoped>

</style>
